<template>
  <div class="main">
    <el-row :gutter="20">
      <el-col :span="4">
        <p class="label-form"> 用户名称：</p>
        <el-input v-model="queryParams.nickName" placeholder="请输入用户名称"></el-input>
      </el-col>
      <el-col :span="4">
        <p class="label-form"> 手机号：</p>
        <el-input v-model="queryParams.phone" placeholder="请输入手机号"></el-input>
      </el-col>
      <el-col :span="4">
        <p class="label-form"> 状态：</p>
        <el-select style="width: 100%;" clearable v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <p class="label-form"></p>
        <el-button type="primary" @click="getSelect" icon="el-icon-search">搜索</el-button>
        <el-button type="warning" @click="resert" icon="el-icon-refresh-right">重置</el-button>
      </el-col>
    </el-row>

<!--    <el-row :gutter="20" style="margin-top: 10px">-->
<!--      <el-col :span="4">-->
<!--        <el-button type="primary" icon="el-icon-plus">新增商铺</el-button>-->
<!--      </el-col>-->
<!--    </el-row>-->

    <el-table :data="tableData"  row-key="id" :expand-row-keys="expandedRowKeys" border @expand-change="handleExpand" max-height="600" style="margin-top: 30px">
      <el-table-column type="expand" >
        <template slot-scope="props">
          <div style="padding: 20px;box-sizing: border-box">
            <el-table
              :data="tableCarList"
              border
              style="width: 800px">
              <el-table-column prop="model" label="汽车名称"></el-table-column>
              <el-table-column prop="img" label="车辆图片">
                <template slot-scope="scope">
                  <el-image style="height: 50px;object-fit: contain" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="licensePlate" label="车牌号"></el-table-column>

              <el-table-column  label="查看轮胎">
                <template slot-scope="scope">
                  <el-button size="mini" @click="openView(scope.row)">查看</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="状态">
                <template slot-scope="scope">
                  {{scope.row.status === 1 ? '使用中':'未使用'}}
                </template>
              </el-table-column>
              <el-table-column prop="id"  width="180" label="营运车辆">
                <template slot-scope="scope">
                  {{/1/.test(scope.row.extInfo) ? '是':'否'}}
                </template>
              </el-table-column>
              <el-table-column prop="type" align="center" label="操作" min-width="100" fixed="right">
                <template slot-scope="scope">
                  <el-button @click="updaeUserCars(scope.row)" type="danger" size="mini" icon="el-icon-delete">解除绑定</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" width="80" label="ID"></el-table-column>
      <el-table-column prop="nickname" min-width="150" label="用户昵称"></el-table-column>
      <el-table-column align="center" width="100" label="用户头像">
        <template slot-scope="scope">
          <el-image style="width: 60px;height: 60px;border-radius: 50%" :src="scope.row.icon"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="phone" width="150" label="手机号"></el-table-column>
      <el-table-column prop="status" align="center" label="用户状态">
        <template slot-scope="scope">
          {{status(scope.row.status)}}
        </template>
      </el-table-column>
      <el-table-column align="center" width="150" label="用户权限">
        <template slot-scope="scope">
          {{scope.row.role ===1 ? '普通用户':scope.row.role ===2 ? '管理员':'合作商家'}}
        </template>
      </el-table-column>
      <el-table-column prop="carNum" min-width="150" label="已绑定车辆">
        <template slot-scope="scope">
          <p>已绑定： {{scope.row.carNum}} 辆车</p>
<!--          <el-button type="primary" @click="bandCar(scope.row)" size="mini" icon="el-icon-plus">添加车辆</el-button>-->
        </template>
      </el-table-column>
      <el-table-column prop="createTime" min-width="150" label="创建时间"></el-table-column>
      <el-table-column fixed="right" width="200" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-edit"  @click="openRole(scope.row)">权限设置</el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="updateUser(scope.row)">修改</el-button>
          <el-button type="text" size="mini" icon="el-icon-view" @click="viewUser(scope.row)">查看</el-button>
          <el-button type="text" @click="updateUsers(scope.row,0)" v-if="scope.row.status===1" size="mini" icon="el-icon-close">禁用</el-button>
          <el-button type="text" @click="updateUsers(scope.row,1)" size="mini" v-if="scope.row.status===0" icon="el-icon-open">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="提示"
      :visible.sync="isAdmin"
      width="30%"
      :before-close="handleCloseAdmin">
      用户权限设置
      <el-radio-group v-model="role">
        <el-radio :label="1">普通用户</el-radio>
        <el-radio :label="2">管理员</el-radio>
        <el-radio :label="3">合作商家</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
    <el-button @click="handleCloseAdmin">取消</el-button>
    <el-button type="primary" @click="setAdmin">确 定</el-button>
  </span>
    </el-dialog>


    <el-dialog
      :title="isEdit ? '修改-用户基本信息':'查看-用户基本信息'"
      :visible.sync="dialogVisible"
      width="1200px"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户昵称">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户头像">

          <el-upload
            action=""
            :http-request="uploadFile"
            list-type="picture-card"
            :limit="1"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
<!--          <image-upload :limit="1" :isShowTip="false" v-model="form.icon"></image-upload>-->
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆">
          <el-table
            :data="carList"
            border
            style="">
            <el-table-column prop="model" label="汽车名称"></el-table-column>
            <el-table-column prop="img" label="车辆图片">
              <template slot-scope="scope">
                <el-image :src="scope.row.img" style="height: 50px" :preview-src-list="[scope.row.img]"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="licensePlate" label="车牌号"></el-table-column>
            <el-table-column prop="extInfo" label="备注"></el-table-column>
<!--            <el-table-column prop="storeName" label="已绑定门店"></el-table-column>-->
<!--            <el-table-column prop="storeAddress" label="门店地址"></el-table-column>-->
<!--            <el-table-column prop="storePhone" label="门店联系方式"></el-table-column>-->

          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="isEdit" @click="closeBtn">取消</el-button>
        <el-button v-if="isEdit" type="primary" @click="submitEditUser">确定</el-button>
        <el-button v-if="!isEdit" type="primary" @click="closeBtn">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="绑定车辆"
      :visible.sync="dialogVisibleCar"
      width="600px"
      :before-close="closeCar">
      <el-form ref="form" :model="formData" label-width="80px">
        <el-form-item label="车牌号" placeholder="车牌号">
          <el-input v-model="formData.licensePlate"></el-input>
        </el-form-item>
        <el-form-item label="车辆照片">
          <lz-upload :img-src="formData.img" :limit="1" @uploadImage="uploadImage"></lz-upload>
        </el-form-item>
        <el-form-item label="车辆型号">
          <el-input v-model="formData.model" placeholder="车辆名称+型号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.extInfo"></el-input>
        </el-form-item>
        <el-form-item label="轮胎品牌">
          <el-select
            style="width: 100%;"
            v-model="formData.brandId"
            clearable
            placeholder="请选择轮胎">
            <el-option
              v-for="item in optionsBrand"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店">
          <el-select
            style="width: 100%;"
            v-model="formData.storeId"
            clearable
            placeholder="请选择门店">
            <el-option
              v-for="item in optionsStore"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>

      </span>


    </el-dialog>
    <div class="box-pager">
      <pagination
        v-show="pager.total>0"
        :total="pager.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getListsPage"
      />

    </div>


    <el-dialog
      title="轮胎信息"
      :visible.sync="payStatus"
      width="1200px"
      :before-close="handleClosePayStatus">
      <el-table
        :data="tyreListArray"
        border
        style="width: 100%">
        <el-table-column prop="code" label="条形码" min-width="150">  </el-table-column>
        <el-table-column prop="patnm" label="花纹" min-width="150"> </el-table-column>
        <el-table-column prop="spcnm" label="规格" min-width="150"></el-table-column>
        <el-table-column prop="dot" label="DOT" min-width="150"></el-table-column>
        <el-table-column prop="brnm" label="品牌" min-width="150"></el-table-column>
        <el-table-column prop="erpid" label="物料编码" min-width="150"></el-table-column>
        <el-table-column prop="scmnm" label="客户编码" min-width="150"></el-table-column>
        <el-table-column prop="createTime" label="安装时间" min-width="180">
          <template slot-scope="scope">

            {{parseTime(scope.row.createTime)}}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="轮胎位置" min-width="150">
          <template slot-scope="scope">

            {{position(scope.row.position)}}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="是否允许理赔" min-width="150">
          <template slot-scope="scope">

            {{scope.row.isReparation ===1 ? '否':'是'}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="120" align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="deleteTyre(scope.row)" icon="el-icon-delete" size="mini">删除记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">

        <el-button type="primary" @click="payStatus = false">关闭</el-button>
      </span>
    </el-dialog>
    <div class="safe"></div>
  </div>
</template>

<script>
import {
  addCar,
  carListUserId, deleteCardRecord,
  getStoreList, getTyreById,
  getTyreList,
  getUserList, tyreInstallLogList2,
  updateUserCar,
  updateUserInfo,
  uploadImage
} from '@/api/apiFox'
import {usePaging} from "@/api/usePage";
import { parseTime } from '../../../../utils/ruoyi'

export default {
  data() {
    return {
      payStatus:false,
      tyreListArray:[],
      openValue:{},


      currentPage1: 5,
      dialogVisible:false,
      dialogVisibleCar:false,
      isImageDialogVisible:false,
      dialogImageUrl:"",
      value1:'',
      pager:{
        total:100
      },
      isEdit:false,

      tableData: [],
      tableCarList:[],
      carList:[],
      options: [
        {value: "", label: '全部'},
        {value: 0, label: '禁用'},
        {value: 1, label: '启用'},
      ],
      optionsBrand:[],
      optionsStore:[],
      value: '',
      form: {},
      carForm:{},
      formData:{
        userId:"",
        brandId:"",
        storeId:"",
        model:"",
        licensePlate:"",
        img:"",
        extInfo:""
      },
      expandedRowKeys:[],
      fileList:[],
      queryParams:{
        pageNum:1,
        pageSize:10,
        nickName:"",
        phone:"",
        status:""
      },
      isAdmin:false,
      role:1
    }
  },

  mounted() {
    this.getLists(this.queryParams)
    this.getBaseInfo()
  },
  methods: {
    parseTime,
    position(val) {
      switch (val) {
        case 1: {
          return '左前'
        }
        case 2: {
          return '右前'
        }
        case 3: {
          return '左后'
        }
        case 4: {
          return '右后'
        }
      }
    },
    openView(item){
      this.openValue = item
      getTyreById({carId:item.id}).then(res=>{
      // tyreInstallLogList2({requestId:item.id}).then(res=>{
        this.tyreListArray = res
        this.payStatus = true
      }).catch(err=>{
        this.payStatus = false
        this.tyreListArray = []
      })
    },

    handleClosePayStatus(){
      this.payStatus = false
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.isImageDialogVisible = true;
    },
    uploadFile(file){
      uploadImage(file.file).then(res=>{
        this.form.icon = res.msg
        this.fileList = [{
          name: res,
          url: res.msg,  // 图片URL
        }];
      })
    },
    closeBtn(){
      this.dialogVisible=false
      this.form = {}
    },
    submitEditUser(){
      console.log(this.form)
      updateUserInfo(this.form).then(res=>{
        this.$message.success('修改成功')
        this.getLists(this.queryParams)
        this.closeBtn()
      })
    },
    openRole(item){
      this.form = item
      this.isAdmin = true
      this.role = item.role
    },
    setAdmin(){
      updateUserInfo({id:this.form.id,role:this.role}).then(res=>{
        this.$message.success('修改成功')
        this.getLists(this.queryParams)
        this.handleCloseAdmin()
      })
    },
    handleCloseAdmin(){
      this.isAdmin = false
      this.role = 1
    },

    getListsPage(e){
      this.queryParams.pageNum = e.page
      this.queryParams.pageSize = e.limit
      this.getLists(this.queryParams)
    },
    getLists(params){

      getUserList(params).then(res=>{
        console.log(res)
        this.pager.total=res.total
        this.tableData =res.rows
      })
    },

    getBaseInfo(){
      getTyreList().then(res=>{
          this.optionsBrand = res
      })
      getStoreList().then(res=>{
        this.optionsStore = res
      })

    },

    updateUsers(row,status){
      //禁用
      if (status===0){
        updateUserInfo({id:row.id,status:0}).then(res=>{
          this.$message.success('禁用成功')
          this.getLists(this.queryParams)
        })
      }else{
        updateUserInfo({id:row.id,status:1}).then(res=>{
          this.$message.success('已启用')
          this.getLists(this.queryParams)
        })
      }
    },

    getSelect(){
      this.getLists(this.queryParams)
    },
    resert(){
      this.queryParams={
          pageNum:1,
          pageSize:10,
          nickName:"",
          phone:"",
          status:""
      }
      this.getLists(this.queryParams)
    },

    handleExpand(row,expandedRows) {
      this.carForm=row
      const currentRowId = row.id;
      const index = this.expandedRowKeys.indexOf(currentRowId);
      if (index === -1) {
        // 如果当前行没有展开，则展开此行
        this.expandedRowKeys = [currentRowId];
      } else {
        // 如果当前行已经展开，关闭该行
        this.expandedRowKeys = [];
      }
      carListUserId({userId:row.id}).then(res=>{
        this.tableCarList = res
      })
    },


    updateUser(item){
      this.dialogVisible = true
      this.form = item
      this.getListUser(item)
      this.fileList = [{
        name: this.form.icon,
        url: this.form.icon,  // 图片URL
      }];
      this.isEdit = true
    },
    getListUser(item){
      carListUserId({userId:item.id}).then(res=>{
        this.carList = res
      })
    },
    viewUser(item){
      this.dialogVisible = true
      this.form = item
      this.isEdit = false
      this.fileList = [{
        name: this.form.icon,
        url: this.form.icon,  // 图片URL
      }];
      this.getListUser(item)
    },
    deleteForm(item){
      console.log(item)
      this.openValue = item
      getTyreById({carId:item.id}).then(res=>{
        if (res && res.length>0){
          this.$confirm('当前车辆已安装轮胎，请先解绑轮胎后再删除车辆', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

           this.openView(item)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }else{
          updateUserCar({id:item.id,isdelete:1}).then(res=>{
            this.$message.success('解绑成功')
            this.getListUser(this.carForm)

          })
        }
      }).catch(err=>{})
    },
    //删除轮胎信息
    deleteTyre(item){
      deleteCardRecord(item.id).then(res=>{
        this.$message.success('删除成功')
        this.getTyreRecordList(this.openValue)
      }).catch(err=>{
        this.getTyreRecordList(this.openValue)
      })
    },

    getTyreRecordList(item){
      getTyreById({carId:item.id}).then(res=>{
        this.tyreListArray = res
      }).catch(err=>{
        this.tyreListArray = []
      })
    },

    updaeUserCars(row){
      console.log(row)
      this.deleteForm(row)

    },

    uploadImage(e){
      this.formData.img = e
    },

    cancel(){
      this.dialogVisibleCar=false
      this.formData={}
    },

    submitForm(){
      console.log(this.formData)
      if (!this.formData.licensePlate){
        this.$message.error('车牌号必填')
        return
      }
      if (!this.formData.img){
        this.$message.error('车辆照片没有上传')
        return
      }
      if (!this.formData.model){
        this.$message.error('型号必填')
        return
      }
      if (!this.formData.extInfo){
        this.$message.error('填写备注')
        return
      }
      if (!this.formData.brandId){
        this.$message.error('轮胎品牌必填')
        return
      }
      if (!this.formData.storeId){
        this.$message.error('请先选择店铺')
        return
      }
      let t = this.optionsBrand.filter(value => {return  value.id === this.formData.brandId })
      if (t && t.length>0){
        this.formData.brand = t[0].name
      }else{
        this.formData.brand = ""
      }

      addCar(this.formData).then(res=>{
        this.$message.success('绑定成功')
        this.getLists(this.queryParams)
        this.cancel()
      })
    },

    handleClose(){
      this.dialogVisible=false
    },
    bandCar(e){
      this.dialogVisibleCar=true
      this.formData.userId = e.id
    },
    closeCar(){
      this.dialogVisibleCar=false
    },
    status(val){
      switch (val){
        case 0:{
          return '禁用'
        }
        case 1:{
          return '启用'
        }
      }
    },

  },
}
</script>


<style scoped lang="scss">
.main{
  width: 100%;
  min-height: 100vh;
  padding: 30px;
  box-sizing: border-box;
  .label{
    font-size: 14px;
    height: 20px;
    margin-bottom: 5px;
  }
}
.grid-content{
  height: 40px;
  text-align: right;
  line-height: 40px;
}
.bg-purple{
  font-size: 14px;
  color: #3f3f3f;
}
</style>
